#include <QtGui>
#include <QtXml>
#include "stage2.h"
#include "attribute.h"
//
Stage2::Stage2() : Stage()
{
	_tree = 0;
}
//
void Stage2::clear()
{
	_tree->clear();
}
void Stage2::setTreeWidget(DragTreeWidget *tv)
{
	_tree = tv;
	_tree->setAttributes(attrModel());
}
// сохранение ветви дерева
void saveItem(QDomElement *elem, QTreeWidgetItem *item)
{
	QDomElement newelem;
	QDomDocument doc;
	newelem = doc.createElement("item");
	newelem.setAttribute("order",item->data(0,Qt::UserRole).toInt());
	for(int i=0;i<item->childCount();i++){
		saveItem(&newelem,item->child(i));
	}
	elem->appendChild(newelem);
}
//
QDomElement Stage2::xml()
{
	QDomElement node;
	QDomDocument doc;
	node = doc.createElement("stage2");
	
	for(int i=0;i<_tree->topLevelItemCount();i++){
		QTreeWidgetItem *item = _tree->topLevelItem(i);
		saveItem(&node,item);		
	}
	
	return node;	
}
//
void Stage2::loadElement(QDomElement *elem,QTreeWidgetItem *pitem)
{
	if(!elem) return;
	QDomElement e = elem->firstChildElement("item");
	while(!e.isNull()){
		Attribute *dl = attribute(e.attribute("order").toInt());
		if(dl){
			QTreeWidgetItem *item = new QTreeWidgetItem(pitem,QStringList() << dl->alias());
			item->setData(0,Qt::UserRole,dl->order());
			loadElement(&e,item);
			if(item->childCount())
				dl->setPlus(true);
			item->setExpanded(true);
		}
		e = e.nextSiblingElement("item");
	}
	
}
//
bool Stage2::load(QDomElement elem)
{
	if(elem.isNull()) return false;
	QDomElement e = elem.firstChildElement("item");
	while(!e.isNull()){
		Attribute *dl = attribute(e.attribute("order").toInt());
		if(dl){
			QTreeWidgetItem *item = new QTreeWidgetItem(_tree,QStringList() << dl->alias());
			item->setFlags(item->flags() | Qt::ItemIsDragEnabled);
			item->setData(0,Qt::UserRole,dl->order());				
			loadElement(&e,item);
			if(item->childCount())
				dl->setPlus(true);
			
			_tree->expandItem(item);			
		}
		e = e.nextSiblingElement("item");
	}
	
	return true;
}

//
void Stage2::slotAttrChanged(int oldnom,Attribute *label)
{
	for(int i=0;i<_tree->topLevelItemCount();i++){
		QTreeWidgetItem *item = _tree->topLevelItem(i);
		if(changeAttribute(oldnom,label,item)) break;
	}		
}

